package com.kaikeba.estack.web.controller;


import com.google.common.collect.ImmutableMap;
import com.kaikeba.estack.bean.Message;
import com.kaikeba.estack.bean.User;
import com.kaikeba.estack.common.util.RSAUtils;
import com.kaikeba.estack.service.UserService;
import com.kaikeba.estack.web.SecurityFacade;
import com.kaikeba.estack.web.constant.ErrorConstant;
import com.kaikeba.estack.web.mvc.Controller;
import com.kaikeba.estack.web.mvc.RequestMapping;
import com.kaikeba.estack.web.mvc.RequestParam;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    /**
     * 登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public Message login(@RequestParam("username") String username,
                         @RequestParam("password") String password,
                         HttpServletRequest request) {
        //1.    接参数
        try {
            password = RSAUtils.decryptStringByJs(password);
        } catch (Exception e) {
            logger.error("用户[{}]登录解析密码失败", username, e);
            return ErrorConstant.ADMIN_LOGIN_PASSWORD_RESOLVE_ERROR.toMessage();
        }

        //2.    调用Service传参数，并获取结果
        List<User> resultList = UserService.queryUserByUsernamePassword(username, password);
        if (resultList == null || resultList.size() == 0 || resultList.size() > 1) {
            logger.info("用户[{}]登录失败,resultList:[{}]", username, resultList);
            return ErrorConstant.ADMIN_LOGIN_FAILED.toMessage();
        }
        //登录时间 和 ip的更新
        Date date = new Date();
        String ip = request.getRemoteAddr();
        UserService.updateLoginTimeAndIP(username, date, ip);
        SecurityFacade.setCurrentUser(resultList.get(0));
        return Message.ok();
    }

    /**
     * 获取RSA加密的公钥
     *
     * @return
     */
    @RequestMapping("/getPublicKey")
    public Message<Map<String, Object>> getPublicKey() {
        RSAPublicKey publicKey = RSAUtils.getDefaultPublicKey();
        String modulus = new String(Hex.encode(publicKey.getModulus()
                .toByteArray()));
        String exponent = new String(Hex.encode(publicKey.getPublicExponent()
                .toByteArray()));
        return Message.ok(ImmutableMap.of("modulus", modulus, "exponent", exponent));
    }


    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("/logout")
    public Message logout() {
        SecurityFacade.logout();
        return Message.ok();
    }

}
